package com.zjs.jsp.status.scheduling;

import com.zjs.jsp.domain.stats.Msgnt;
import com.zjs.jsp.domain.stats.OrderStatus;
import com.zjs.jsp.domain.stats.StatusRoot;
import com.zjs.jsp.status.mongodb.jsp_orderstatusRepository;
import com.zjs.jsp.status.service.ProcessingService;
import com.zjs.jsp.status.service.SendCloudService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author 李文
 * @create 2018-07-23 16:00
 **/
@Component
public class StatusRepeatScheduling
{


    private static final Logger LOGGER = LoggerFactory.getLogger(StatusRepeatScheduling.class);

    @Autowired
    SendCloudService sendCloudService;

    private final String JSPSTATUS = "orderStatus";

    @Autowired
    private MongoTemplate template;

    @Autowired
    private ProcessingService pr;

    @Autowired
    private jsp_orderstatusRepository orderstatusRepository;


    @Scheduled(fixedDelay = 30000)
    public void repeatstatus() {
        String uuid = UUID.randomUUID().toString().replace("-", "");
        LOGGER.info("{} 开始查询需要重新推送的信息", uuid);
        // 1获取数据库信息

        try {
            long start = System.currentTimeMillis();
            List<OrderStatus> jsplist = new ArrayList<>();
            try {
                jsplist = orderstatusRepository.findTop100BySuOrderByTsuAsc(0);
            } catch (Exception e) {
                LOGGER.info("{}  查询数据库 出现异常", uuid, e);
            }
            if (jsplist != null && jsplist.size() > 0) {
                LOGGER.info("{} 查询到要推送的数据条数Count:{}", uuid, jsplist.size());
                // 2推送
                // 3更新状态
                for (OrderStatus orderStatus : jsplist) {
                    sendOrderStatus(uuid, orderStatus);
                    LOGGER.info(" {} 推送更新完成耗时 :{}", uuid, System.currentTimeMillis() - start);
                }
            } else {
                LOGGER.info("{} 没有查到需要重新推送的信息", uuid);
            }
        } catch (Exception e) {
            LOGGER.info("{} 出现异常", uuid, e);
        }
    }

    private void sendOrderStatus(String uid, OrderStatus orderStatus) {
        if (orderStatus != null) {
            String uuid = orderStatus.getId();
            try {
                if (pr.isExistsStatusOver(orderStatus)) {
                    // 配置文件  写明映射关系
                    if (sendCloudService.PushMessageHandle(uuid, orderStatus)) {
                        LOGGER.info(" {} 重推推送成功 {}", uuid, orderStatus.toString());
                        Query query1 = new Query(new Criteria("_id").is(orderStatus.getId()));
                        Update update = new Update().set("su", 1).set("date", new Date());
                        template.updateFirst(query1, update, JSPSTATUS);
                    }
                } else {
                    saveOrderStatus(uuid, orderStatus);
                    LOGGER.warn("{} 等待发送状态有之前的状态为发送{}", uuid, orderStatus.toString());

                }
            } catch (Exception e) {
                LOGGER.warn("{} 出现异常 {}", uuid, orderStatus.toString());
            }

        } else {
            LOGGER.info(" {} 数据为空", uid);
        }
    }

    private void saveOrderStatus(String uuid, OrderStatus orderStatus) throws Exception {
        Integer os = ProcessingService.status.get(orderStatus.getOs());
        StatusRoot sr = pr.getOrderStatus(uuid, orderStatus.getPoc(), os.toString());
        if (sr.getData() != null) {
            OrderStatus status = sr.getData().toOrderStatus();
            // 获取骑手信息
            Msgnt m = pr.getRiderInformation(sr);
            status.setLat(m.getLat());
            status.setLng(m.getLng());
            status.setSu(0);
            orderstatusRepository.save(status);
        }
    }
}


